package freespiritsocial.io.user.ui.fragment.account

import android.content.Intent
import android.os.Bundle
import androidx.core.os.bundleOf
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.login.LoginManager
import com.facebook.login.LoginResult
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import freespiritsocial.io.user.R
import freespiritsocial.io.user.base.BaseFragment
import freespiritsocial.io.user.databinding.FrgLoginBinding
import freespiritsocial.io.user.ext.goMain
import freespiritsocial.io.user.ui.activity.MainAct
import freespiritsocial.io.user.util.CacheUtil
import freespiritsocial.io.user.viewmodel.LoginViewModel
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction

class LoginFrg: BaseFragment<LoginViewModel,FrgLoginBinding>() {
    override fun layoutId(): Int = R.layout.frg_login

    companion object {

        const val RC_SIGN_IN = 10000
    }

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.countryCode.set(mDatabind.includedPhone.ccp.selectedCountryCodeWithPlus)
        mDatabind.viewModel = mViewModel
        mDatabind.click = Click()
        initCcp()
    }

    val act by lazy {
        activity as MainAct
    }

    override fun onActivityResult(requestCode: Int,resultCode: Int,data: Intent?) {
        if (requestCode == RC_SIGN_IN) {
            GoogleSignIn.getSignedInAccountFromIntent(data).runCatching {
                getResult(ApiException::class.java)
            }.onSuccess {
                mViewModel.google(it.id?:"",{
                    nav().navigateAction(R.id.signSup2UpFrg,bundleOf("thirdPartyType" to 2,SignSup2UpFrg.key_third_name to it.id))
                },{
                    CacheUtil.token = it
                    nav().goMain()
                })
                client?.signOut()
            }.onFailure {
                it.printStackTrace()
            }
        }
        super.onActivityResult(requestCode,resultCode,data)
    }

    private fun initFacebook() {
        LoginManager.getInstance()
            .registerCallback(act.callbackManager,object: FacebookCallback<LoginResult> {
                override fun onSuccess(result: LoginResult?) {
                    if (isHidden) return
                    result?.accessToken?.userId?.let { userid ->
                        mViewModel.faceBook(userid,{
                            nav().navigateAction(R.id.signSup2UpFrg,bundleOf("thirdPartyType" to 3,SignSup2UpFrg.key_third_name to userid))
                        },{
                            CacheUtil.token = it
                            nav().goMain()
                        })
                    }
                    LoginManager.getInstance().logOut()
                }

                override fun onCancel() {
                }

                override fun onError(error: FacebookException?) {
                    mViewModel.toast.postValue(error?.message)
                }
            })

    }

    var client: GoogleSignInClient? = null
    override fun onDestroyView() {
        LoginManager.getInstance().unregisterCallback(act.callbackManager)
        super.onDestroyView()
    }

    private fun initCcp() {
//        mDatabind.includedPhone.ccp.registerCarrierNumberEditText(mDatabind.includedPhone.etPhoneNumber)
        mDatabind.includedPhone.ccp.setOnCountryChangeListener {
            mViewModel.countryCode.set(mDatabind.includedPhone.ccp.selectedCountryCodeWithPlus)
        }
    }

    inner class Click {
        fun forgotPassword() {
            nav().navigateAction(R.id.action_loginFrg_to_forgotFrg)
        }

        fun signUp() {
            nav().navigateAction(R.id.action_loginFrg_to_signUpFrg)
        }

        fun login() {
            mViewModel.login {
                CacheUtil.token = it
                nav().goMain()
            }
        }

        fun loginWithGoogle() {
            val gso =
                GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                    .requestIdToken(getString(R.string.server_client_id))
                    .requestId()
                    .build()
            client = GoogleSignIn.getClient(requireContext(),gso)
            val signInIntent: Intent? = client?.signInIntent
            startActivityForResult(signInIntent,RC_SIGN_IN)

        }

        fun loginWithFacebook() {
            initFacebook()
            LoginManager.getInstance()
                .logInWithReadPermissions(
                    act,
                    listOf("public_profile")
                )
        }
    }
}